package com.googlecode.afdbaccess.web.common.interceptors;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

@RequestLogged
@Interceptor
public class RequestLoggerInterceptor {
    private final static Logger log = Logger.getLogger(RequestLoggerInterceptor.class);
    
    @AroundInvoke 
    public Object logRequest(InvocationContext invocationContext) throws Exception {
        final long startTimestamp = System.currentTimeMillis();

        String page = null;

        HttpServletRequest request = InterceptorsCommon.findRequest(invocationContext);

        if(request != null) {
            page = InterceptorsCommon.getPageDescription(request);
        }

        if(page != null) {
            logPageRequest(request, page);
        }

        try {
            return invocationContext.proceed();
        } finally {
            if(page != null) {
                log.debug("Page: " + page + " took " + (System.currentTimeMillis()-startTimestamp) + " ms to generate/serve.");
            }
        }
    }

    private void logPageRequest(HttpServletRequest request, String page) {
        String url=request.getRequestURL().toString();
        log.info("Serving page (" + request.getMethod() + ") " + page + " called as " + url);
    }
}